package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.heima.article.ArticleApplication;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.AggBehaviorDTO;
import com.heima.utils.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mrchen
 * @date 2022/7/16 10:24
 */
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void computeHotArticle() {
        // 1. 基于当前时间，查询近5天的文章数据
        // 获取5天之前的时间    2022-7-11 10:31:00    Date   LocalDate  LocalDateTime
        String dateParams = LocalDateTime.now()
                                         .minusDays(5)
                                          .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        List<ApArticle> articleList = apArticleMapper.selectArticleByDate(dateParams);
        if(CollectionUtils.isEmpty(articleList)){
            log.info("当前头条APP太冷清了，近5天没人发表文章。。。。。");
            return;
        }
        // 2. 遍历文章列表，计算文章热度分值
        List<HotArticleVo> hotArticleVoList = getHotArticleVOList(articleList);

        // 3. 按频道缓存热点文章
        cacheRedisByTag(hotArticleVoList);

    }

    @Override
    public void updateApArticle(AggBehaviorDTO aggBehavior) {
        // 1. 根据文章id查询文章对象
        ApArticle article = apArticleMapper.selectById(aggBehavior.getArticleId());
        if(article == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"对应的文章信息不存在");
        }
        // 2. 根据行为聚合结果，修改文章各行为的统计值
        article.setViews((int)(article.getViews() + aggBehavior.getView()));
        article.setLikes((int)(article.getLikes() + aggBehavior.getLike()));
        article.setComment((int)(article.getComment() + aggBehavior.getComment()));
        article.setCollection((int)(article.getCollection() + aggBehavior.getCollect()));
        apArticleMapper.updateById(article);
        // 3. 重新计算文章热度得分
        Integer score = computeScore(article);
        // 4. 判断是否当日发布文章，如果是: 整体热度 * 3
        String now = DateUtils.dateToString(new Date());
        String publish = DateUtils.dateToString(article.getPublishTime());
        if (now.equals(publish)) {
            score = score * 3;
        }
        // 5. TODO 更新所在频道 热点文章缓存
        updateArticleCache(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + article.getChannelId(),article,score);
        // 6. TODO 更新推荐频道 热点文章缓存
        updateArticleCache(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG,article,score);
    }

    /**
     * @param cacheKey  缓存的key
     * @param article   更新完热度的文章对象
     * @param score     最新的热度值
     */
    private void updateArticleCache(String cacheKey, ApArticle article, Integer score) {
        // 1. 根据缓存的key查询对应 缓存列表    [{},{},{}]
        String jsonStr = redisTemplate.opsForValue().get(cacheKey);
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
        // 2. 判断当前文章是否已经是热点文章
        boolean flag = false;
        for (HotArticleVo articleVo : hotArticleVoList) {
            if(articleVo.getId().equals(article.getId())){
                // 如果是 直接更新文章热度值
                articleVo.setScore(score);
                flag = true;
                break;
            }
        }
        // 3. 如果没有存在热点文章中
        if(!flag){
            // 将当前文章直接加入到热点文章集合中
            HotArticleVo articleVo = new HotArticleVo();
            BeanUtils.copyProperties(article,articleVo);
            articleVo.setScore(score);
            hotArticleVoList.add(articleVo);
        }
        // 4. 将文章按照热度降序排序，并且截取前30条文章
        hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).limit(30).collect(Collectors.toList());
        // 5. 将最新的热点文章缓存到redis中  更新热点文章缓存
        redisTemplate.opsForValue().set(cacheKey,JSON.toJSONString(hotArticleVoList));
    }


    @Autowired
    AdminFeign adminFeign;

    /**
     * 将文章  按照频道 缓存到redis中
     * @param hotArticleVoList
     */
    private void cacheRedisByTag(List<HotArticleVo> hotArticleVoList) {
        // 1. 远程查询频道列表
        ResponseResult<List<AdChannel>> result = adminFeign.selectChannels();
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        List<AdChannel> channelList = result.getData();
        // 2. 为每个频道缓存文章
        for (AdChannel channel : channelList) {
            List<HotArticleVo> hotArticleListByChannel = hotArticleVoList.stream()
                    .filter(hotArticleVo -> hotArticleVo.getChannelId().equals(channel.getId()))
                    .collect(Collectors.toList());
            // 缓存文章
            sortAndCache(hotArticleListByChannel,ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channel.getId());

        }
        // 3. 为推荐频道缓存文章
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 缓存到redis
     * @param hotArticleVoList
     * @param cacheKey
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVoList, String cacheKey) {
        //1. 将文章 按照热度降序排序   截取前30条文章
        hotArticleVoList = hotArticleVoList.stream()
                // 按照文章热度 降序排序
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                // 截取前30条
                .limit(30)
                .collect(Collectors.toList());
        //2.  String 结构     List<Article>  ==>   [{文章1},{文章2},{文章3}]
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVoList));
    }

    /**
     * 计算每篇文章分值
     * @param articleList
     * @return
     */
    private List<HotArticleVo> getHotArticleVOList(List<ApArticle> articleList) {
        // 1. 遍历文章
        return articleList.stream()
                    .map(apArticle -> {
                        HotArticleVo articleVo = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle,articleVo);
                        // 2. 计算每篇文章的分值
                        articleVo.setScore(computeScore(apArticle));
                        return articleVo;
                    }).collect(Collectors.toList());
        // 3. 将article封装为vo对象
    }

    /**
     * 计算每篇文章的热度得分
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        Integer views = apArticle.getViews();
        if(views!=null){
            score +=  views * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        Integer likes = apArticle.getLikes();
        if(likes!=null){
            score +=  likes * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        Integer comment = apArticle.getComment();
        if(comment!=null){
            score +=  comment * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        Integer collection = apArticle.getCollection();
        if(collection!=null){
            score +=  collection * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
